package com.guochaojava.util;

import cn.hutool.core.lang.Console;
import cn.hutool.http.HttpUtil;
import cn.hutool.json.JSONUtil;
import com.lgd.winter.wechat.content.tecent.bean.result.TecentAccessTokenResult;
import com.lgd.winter.wechat.core.WeChatTemplate;
import org.springframework.data.redis.core.StringRedisTemplate;

import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
import java.util.Set;
import java.util.concurrent.TimeUnit;

/**
 * 小程序模版推送工具类
 *
 * @author guochao
 * @since 1.0.0
 */
public class TemplateUtils {

    public static String PUSH_URL = "https://api.weixin.qq.com/cgi-bin/message/wxopen/template/send?access_token=ACCESS_TOKEN";

    /**
     * 小程序推送模版消息
     *
     * @param weChatTemplate 微信操作对象
     * @param redisTemplate  redis操作对象
     * @param openId         接收者openId
     * @param formId         小程序提交表单id
     * @param path           小程序页面路径
     * @param templateId     推送模版id
     * @param param          模版参数
     * @return 推送结果
     */
    public static boolean miniPush(WeChatTemplate weChatTemplate, StringRedisTemplate redisTemplate, String openId, String formId, String path, String templateId, Map<String, String> param) {
        String token = redisTemplate.opsForValue().get("access_token");
        if (token == null) {
            TecentAccessTokenResult tecentAccessTokenResult = getToken(weChatTemplate);
            if (tecentAccessTokenResult.getErrcode() != 0) {
                return false;
            }
            token = tecentAccessTokenResult.getAccessToken();

            redisTemplate.opsForValue().set("access_token", token, 7000, TimeUnit.SECONDS);
        }

        String url = PUSH_URL.replaceAll("ACCESS_TOKEN", token);

        //构造模板参数
        Map<String, Object> map = new HashMap<>(5);
        map.put("touser", openId);
        map.put("template_id", templateId);
        map.put("page", path);
        map.put("form_id", formId);

        Map<String, Object> data = new HashMap<>(4);
        //遍历处理data数据
        Set<Map.Entry<String, String>> entrySet = param.entrySet();
        Iterator<Map.Entry<String, String>> iterator = entrySet.iterator();
        while (iterator.hasNext()) {
            Map.Entry<String, String> entry = iterator.next();
            Map<String, String> valueMap = new HashMap<>(1);
            valueMap.put("value", entry.getValue());
            data.put(entry.getKey(), valueMap);
        }
        map.put("data", JSONUtil.parseObj(data));

        String a = JSONUtil.toJsonStr(map);
        String jsonString = HttpUtil.post(url, a);
        Console.log(jsonString);
        return true;
    }

    private static TecentAccessTokenResult getToken(WeChatTemplate weChatTemplate) {
        TecentAccessTokenResult tecentAccessTokenResult = weChatTemplate.opsForMini().getAccessToken();
        return tecentAccessTokenResult;
    }
}